package com.lzh.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Base64;
import java.util.LinkedHashMap;

/**
 * @author reborn
 * @create 2020/6/1-22:57
 */
@Configuration
public class ShiroConfig {


    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//        设置安全器
        bean.setSecurityManager(manager);
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        /*
        anon:无需认证就可访问
        authc:必需认证就可访问
        user:必需拥有记住我，才能使用
        perms:拥有对某个资源的权限才能访问
        role:拥有某个角色权限才能访问
         */
//

        map.put("/index", "anon");
        map.put("/", "anon");
        map.put("/regist", "anon");
        map.put("/teaMe", "authc");
        map.put("/selStu", "authc");
        map.put("/toClass", "authc");
        map.put("/t6", "perms[root]");

        bean.setFilterChainDefinitionMap(map);
        bean.setLoginUrl("/index");
        return bean;
    }

    public SimpleCookie simpleCookie(){
        SimpleCookie cookie = new SimpleCookie("remenberMe");
        cookie.setMaxAge(7200);
        return cookie;
    }

    public CookieRememberMeManager cookieRememberMeManager(){
        CookieRememberMeManager cookieManager = new CookieRememberMeManager();
        cookieManager.setCookie(simpleCookie());
        return cookieManager;
    }

    //    SecurityManager 关联realm
    @Bean(name = "manager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRememberMeManager(cookieRememberMeManager());
//        securityManager.setRealm(userRealm());
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //    创建reaml对象
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }


//    整合shiroDialect
    @Bean
    public ShiroDialect shiroDialect(){
        return  new ShiroDialect();
    }

}
